package org.vaadin.dotmap.client.ui;

import org.vaadin.dotmap.client.ui.VDotMap.Highlight;
import org.vaadin.dotmap.client.ui.VDotMap.MapLoadListener;

import com.google.gwt.core.client.GWT;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.communication.ClientRpc;
import com.vaadin.terminal.gwt.client.communication.StateChangeEvent;
import com.vaadin.terminal.gwt.client.ui.AbstractComponentConnector;
import com.vaadin.terminal.gwt.client.ui.Connect;

@Connect(org.vaadin.dotmap.DotMap.class)
public class DotMapConnector extends AbstractComponentConnector {

    public static final String ATTR_MAP_IMAGE = "img";
    public static final String ATTR_MAP_COLOR = "bg";
    public static final String ATTR_MAP_TOP_CROP = "tc";
    public static final String ATTR_HIGHLIGHT_IMAGE = "hl";
    public static final String ATTR_HIGHLIGHT_ZINDEX = "z";
    public static final String ATTR_FADE_MSEC = "fm";
    public static final String TAG_HIGHLIGHT = "hl";

    protected String highlightImage;
    protected int fadeMsec = 5000;

    protected ApplicationConnection client;

    public static interface HighlightControl extends ClientRpc {
        public void showHighlight(Highlight h);
    }

    @Override
    protected void init() {
        super.init();

        client = getConnection();

        registerRpc(HighlightControl.class, new HighlightControl() {
            public void showHighlight(Highlight h) {
                // use default or translate
                if (h.getImg() == null) {
                    h.setImg(highlightImage);
                } else {
                    h.setImg(client.translateVaadinUri(h.getImg()));
                }
                getWidget().addHighligt(h);
            }
        });

        getWidget().addListener(new MapLoadListener() {
            public void loaded() {
                getLayoutManager().setNeedsMeasure(DotMapConnector.this);
            }
        });
    }

    @Override
    public void onStateChanged(StateChangeEvent stateChangeEvent) {
        super.onStateChanged(stateChangeEvent);

        getWidget().getElement().getStyle()
                .setBackgroundColor(getState().getMapColor());

        getWidget().setMapUrl(getState().getMapImage().getURL());

        getWidget().setTopCrop(getState().getTopCrop());

    }

    @Override
    public DotMapState getState() {
        return (DotMapState) super.getState();
    }

    @Override
    protected VDotMap createWidget() {
        return GWT.create(VDotMap.class);
    }

    @Override
    public VDotMap getWidget() {
        return (VDotMap) super.getWidget();
    }

}
